package com.ruoyi.teaching.service.impl;

import java.time.LocalDate;
import java.util.List;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.teaching.bo.CheckAnswerResultBo;
import com.ruoyi.teaching.bo.DailyTaskInterviewBo;
import com.ruoyi.teaching.domain.Student;
import com.ruoyi.teaching.domain.YaTeachingPlan;
import com.ruoyi.teaching.enums.DailyTasksStatus;
import com.ruoyi.teaching.mapper.StudentMapper;
import com.ruoyi.teaching.mapper.YaTeachingPlanMapper;
import com.ruoyi.teaching.service.LargeModelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.teaching.mapper.DailyTasksMapper;
import com.ruoyi.teaching.domain.DailyTasks;
import com.ruoyi.teaching.service.IDailyTasksService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 每日任务Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-12
 */
@Slf4j
@Service
public class DailyTasksServiceImpl implements IDailyTasksService
{
    @Autowired
    private DailyTasksMapper dailyTasksMapper;

    @Autowired
    private YaTeachingPlanMapper yaTeachingPlanMapper;

    @Autowired
    private StudentMapper studentMapper;
    /**
     * 查询每日任务
     *
     * @param id 每日任务主键
     * @return 每日任务
     */
    @Override
    public DailyTasks selectDailyTasksById(Long id)
    {
        return dailyTasksMapper.selectDailyTasksById(id);
    }

    /**
     * 查询每日任务列表
     *
     * @param dailyTasks 每日任务
     * @return 每日任务
     */
    @Override
    public List<DailyTasks> selectDailyTasksList(DailyTasks dailyTasks)
    {
        //查询当前学员自己的&&根据日期倒序
        dailyTasks.setStudentId(SecurityUtils.getUserId());
        return dailyTasksMapper.selectDailyTasksList(dailyTasks);
    }

    /**
     * 新增每日任务
     *
     * @param dailyTasks 每日任务
     * @return 结果
     */
    @Override
    public int insertDailyTasks(DailyTasks dailyTasks)
    {
        dailyTasks.setCreateTime(DateUtils.getNowDate());
        return dailyTasksMapper.insertDailyTasks(dailyTasks);
    }

    /**
     * 修改每日任务
     *
     * @param dailyTasks 每日任务
     * @return 结果
     */
    @Override
    public int updateDailyTasks(DailyTasks dailyTasks)
    {
        dailyTasks.setUpdateTime(DateUtils.getNowDate());
        return dailyTasksMapper.updateDailyTasks(dailyTasks);
    }

    /**
     * 批量删除每日任务
     *
     * @param ids 需要删除的每日任务主键
     * @return 结果
     */
    @Override
    public int deleteDailyTasksByIds(Long[] ids)
    {
        return dailyTasksMapper.deleteDailyTasksByIds(ids);
    }

    /**
     * 删除每日任务信息
     *
     * @param id 每日任务主键
     * @return 结果
     */
    @Override
    public int deleteDailyTasksById(Long id)
    {
        return dailyTasksMapper.deleteDailyTasksById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createDailyTasks() {
        String createBy = SecurityUtils.getUsername()==null?"job":SecurityUtils.getUsername();
        //查询到今日所有班级的教学计划
        List<YaTeachingPlan> teachingPlanList = yaTeachingPlanMapper.selectList(new LambdaQueryWrapper<YaTeachingPlan>().eq(YaTeachingPlan::getDate, DateUtils.getDate()));
        //为每个班每个学员创建每日任务
        for (YaTeachingPlan teachingPlan : teachingPlanList) {
            //判断是否工作日
            if (ObjectUtils.isEmpty(teachingPlan.getDay())) {
                continue;
            }
            Long classesId = teachingPlan.getClassesId();
            //查询班级所有学员
            List<Student> studentList = studentMapper.selectList(new LambdaQueryWrapper<Student>().eq(Student::getClassesId, classesId));
            for (Student student : studentList) {
                try{
                    DailyTasks dailyTasks = new DailyTasks();
                    dailyTasks.setStudentId(student.getId());
                    dailyTasks.setClassesId(classesId);
                    dailyTasks.setCreateTime(DateUtils.getNowDate());
                    dailyTasks.setUpdateTime(DateUtils.getNowDate());
                    dailyTasks.setCreateBy(createBy);
                    dailyTasks.setStage(teachingPlan.getStage());
                    dailyTasks.setCourseContent(teachingPlan.getCourseContent());
                    dailyTasks.setDate(teachingPlan.getDate());
                    dailyTasksMapper.insert(dailyTasks);
                }catch (Exception e){
                    log.error("创建每日任务失败，原因：{}",e.getMessage());
                }
            }
        }

    }

    @Override
    public void autoCheckDailyTasks() {
        //根据LocalDate获取到昨日日期字符串(yyyy-MM-dd)
        String yesterday = LocalDate.now().minusDays(1).toString();
        //将昨天未检查的&状态为已提交的任务默认设置为已合格
        dailyTasksMapper.updateQualifiedByDateAndStatus(yesterday, DailyTasksStatus.FINISHED.VALUE, 1);
        //将昨天未提交的任务默认设置为不合格，并且设置为已过期
        dailyTasksMapper.updateUnqualifiedByDateAndStatus(yesterday, DailyTasksStatus.EXPIRED.VALUE, 2);
    }

    @Override
    @Transactional(readOnly = true)
    public List<DailyTaskInterviewBo> queryInterviewList(String date, int interviewType, int classesId) {
        return dailyTasksMapper.queryInterviewList(date, classesId);
    }

    @Autowired
    private LargeModelService largeModelService;

    @Override
    public CheckAnswerResultBo checkAnswer(String question, String answer) {
        try {
            return largeModelService.checkAnswer(question, answer);
        } catch (Exception e) {
            throw new ServiceException("调用大模型api失败:"+e.getMessage());
        }
    }
}
